package com.dingding.web.activity;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.UrlMaker;
import com.dingding.common.core.util.tools.wechat.WechatTool;
import com.dingding.facade.user.service.reg.IUserRegFacade;
import com.dingding.facade.user.service.reg.code.RegUserEnum;
import com.dingding.web.base.action.BaseAction;

/**
 * @Description:注册活动的action
 * @author fengshuonan
 * @date 2016年6月28日 上午10:33:39
 * @version 叮叮搭车
 */
@SuppressWarnings("serial")
public class RegActiveAction extends BaseAction {

	private Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	private IUserRegFacade userRegFacade;  //用户注册接口
	
	/**
	 * @Description:进入注册活动页面
	 * @author fengshuonan
	 * @return String
	 */
	public String startRegActive() {

		// 获取微信跳转的code
		String code = getPara("code");
		
		// 根据code获取微信openId
		String openId = WechatTool.getOpenIDByCode(code);
		
		if(openId != null){
			String url = UrlMaker.getWechatUserRegPageUrl(openId);
			super.write("<script>window.location.href='" + url + "';</script>");
		}
		
		super.write("<script>window.location.href='" + "http://www.pdhz-dddc.cn/dingding-web/regactive/login.html?openId=null" + "';</script>");
		
		return NONE;
	}

	/**
	 * @Description: 获取手机验证码
	 * @author fengshuonan
	 * @return String
	 */
	public String getValidateCode() {
		String tellphone = super.getPara("tellphone");

		boolean flag = super.phonevalidateService.getVerifyCode(tellphone);

		if (flag) {
			super.writeResponseJsonp("success");
		} else {
			super.writeResponseJsonp("error");
		}

		return NONE;
	}

	/**
	 * @Description:完成注册
	 * @author fengshuonan
	 * @return String
	 */
	public String finishReg() {

		String tellphone = super.getPara("tellphone"); // 手机号
		String code = super.getPara("code"); // 验证码
		String openId = super.getPara("openId");//微信公众号id
		
		if(ToolUtil.isBlank(tellphone)){
			super.writeResponseJsonp("phoneNull"); // 电话号码为空
			return NONE;
		}
		
		if(ToolUtil.isBlank(code)){
			super.writeResponseJsonp("codeNull");  //验证码为空
			return NONE;
		}
		
		boolean flag = super.phonevalidateService.verifyCode(tellphone, code);
		if (!flag) {
			super.writeResponseJsonp("codeError"); // 验证码错误
			return NONE;
		}

		// 根据手机号和微信id,注册并赠送优惠券
		RegUserEnum regUserEnum = this.userRegFacade.regUserAndGiveCoupons(tellphone, openId);
		
		//如果已经注册
		if(regUserEnum == RegUserEnum.ALREADY_REG){
			super.writeResponseJsonp("alreadyReg");
			return NONE;
		}
		
		if(regUserEnum == RegUserEnum.FROM_CITY_IS_BEIJING){
			super.writeResponseJsonp("beijingResult");   
		}else if(regUserEnum == RegUserEnum.FROM_CITY_IS_TANGSHAN){
			super.writeResponseJsonp("tangshanResult");  
		}else{
			super.writeResponseJsonp("otherResult");  
		}
		
		return NONE;
	}
}
